package com.itheima.design.mode.cglib_proxy;


import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * 特定的功能增强的实现
 */
public class MyMethodInterceptor implements MethodInterceptor {

    //特定的功能增强实现MyMethodInterceptor里面持有被代理的类或者接口target
    private Object target;

    public MyMethodInterceptor(Object target) {
        this.target = target;
    }

    public Object getTarget() {
        return target;
    }

    public void setTarget(Object target) {
        this.target = target;
    }

    @Override
    //在intercept方法进行调用被代理类或者接口的方法之前进行拦截实现前置、后置、环绕、异常处理等功能的增强
    public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {

        //前置增强
        doSomethingBefore();
        Object res = null;
        if(this.target != null){
            res = method.invoke(target, args);
        }

        //后置增强
        doSomethingAfter();
        return res;
    }

    private void doSomethingBefore() {
        System.out.println("老板你好，这个我试过了，很不错，推荐给你！");
    }

    private void doSomethingAfter() {
        System.out.println("老板你觉得怎样？ 欢迎下次.....");
    }
}
